<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装队列结构</title>
</head>

<body>
    <script>
        /* 
            使用ES6对象语法创建
        */
        class Queue {
            constructor() {
                this.count = 0; // 指向队尾元素
                this.lowstCount = 0; // 队列顶部追踪器
                this.items = {}; // 存储器
            }
            // 向队尾添加一个元素
            enqueue(element) {
                this.items[this.count++] = element;
            }
            // 从队尾删除元素
            dequeue() {
                if (this.isEmpty()) return undefined;
                const res = this.items[this.lowstCount];
                delete this.items[this.lowstCount++];
                return res;
            }
            // 查看队首元素
            peek() {
                if (this.isEmpty()) return undefined;
                return this.items[this.lowstCount];
            }
            // 判断队列是否为空
            isEmpty() {
                return this.size() === 0;
            }
            // 返回长度大小
            size() {
                return this.count - this.lowstCount;
            }
            // 清空队列
            clear() {
                this.lowstCount = 0;
                this.count = 0;
                this.items = {};
            }
            // toString方法
            toString() {
                if (this.isEmpty()) return "";
                let res = "";
                for (let i = this.lowstCount; i < this.count; i++) {
                    res += this.items[i];
                }
                return res;
            }
        }

        let queue1 = new Queue();
        queue1.enqueue(1);
        queue1.enqueue(2);
        queue1.enqueue(3);
        queue1.enqueue(4);
        queue1.peek();
        console.log(queue1.toString());
        queue1.size();
        console.log(queue1.dequeue());
        console.log(queue1.toString());
        queue1.size();


    </script>
</body>

</html>